package leo.data
{
	import flash.geom.Point;
	
	import ghostcat.algorithm.traversal.AStar;
	import ghostcat.algorithm.traversal.MapModel;
	/**
	 * 地图数据 
	 * @author leo
	 * 
	 */
	public class BuildMap
	{
		
		private static var _instance :BuildMap = null;
		private var astar :AStar;
		private var mapModel :MapModel;
		public function BuildMap()
		{
		}
		/**
		 * 初始化地图数据 
		 * 
		 */		
		public function init():void
		{
			var mapAry :Array = GameModel.instance.mapAry;
			var level :int = GameModel.instance.curLevel;

			if(mapAry[level])
			{
				var str :String = mapAry[level] as String;
				var ary :Array = str.split("|");
				var result :Array = [];
				for each(var elem :String in ary)
				{
					result.push(elem.split(","));
				}
				//字符串转成布尔值
				for(var y :int = 0 ; y < result.length; y++)
				{
					for(var x :int = 0; x < result[0].length; x++)
					{
						if(result[y][x] == "true")
						{
							result[y][x] = true;
						}else
						{
							result[y][x] = false;
						}
					}
				}
				GameModel.instance.curMapAry = result;
			}
			
		}
		
		public function addItem(p :Point):void
		{
			if(!p) return;
			GameModel.instance.curMapAry[p.y][p.x] = true;
		}
		
		public function removeItem(p :Point):void
		{
			if(!p) return;
			GameModel.instance.curMapAry[p.y][p.x] = false;
		}
		
		public function checkCanBuild(p :Point):Boolean
		{
		    return GameModel.instance.curMapAry[p.y][p.x];
		}
		
		public function checkIndexInMap(p :Point):Boolean
		{
			return p && p.x >= 0 && p.y >=0 && p.x < GameConst.MAP_COLS && p.y < GameConst.MAP_ROWS;
		}
		/**
		 * 寻路算法 
		 * @param startPoint
		 * @param endPoint
		 * @param mapAry
		 * @return 
		 * 
		 */		
		public function findPath(startPoint :Point,endPoint :Point,mapAry :Array):Array
		{
			
			mapModel = new MapModel(mapAry);
			mapModel.diagonal = false;
			this.astar = new AStar(mapModel);
			return this.astar.find(startPoint,endPoint);
		}

		public static function get instance():BuildMap
		{
			if(_instance == null)
			{
				_instance = new BuildMap();
			}
			return _instance;
		}

	}
}